package com.braveman.im.ui.activity.message;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.braveman.im.R;
import com.braveman.im.bean.JsonNewBean;
import com.braveman.im.bean.PicUpdateBean;
import com.braveman.im.bean.RegisterInfoBean;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.thread.CompressPhotoThread;
import com.braveman.im.ui.weiget.ButtonItem;
import com.braveman.im.ui.weiget.CustomPopwindow;
import com.braveman.im.ui.weiget.DialogUtils;
import com.braveman.im.ui.weiget.DiaogPopup;
import com.braveman.im.utils.GetJsonDataUtil;
import com.braveman.im.utils.PermissionUtils;
import com.braveman.im.utils.UtilsStyle;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.UIUtils;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.vondear.rxtools.RxBarTool;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * 城市选择器
 */
public class RegisterNextActivity extends BaseActivity {

    private QMUIRadiusImageView mIvActivityRegisterHeadIcon;
    private EditText mEtActivityRegisterRealName;
    private EditText mEtActivityRegisterQqInfo;
    private EditText mEtActivityRegisterWeixinInfo;
    private ButtonItem mBtmActivityRegisterPersonInfo;
    private ButtonItem mBtmActivityRegisterIndustry;
    private EditText mEtActivityRegisterCompany;
    private ButtonItem mBtmActivityRegisterCompanyAddress;
    private EditText mEtActivityRegisterWant;
    private TextView mBtnActivityRegisterNext;
    private static final String TAKE_PHOTO_PATH = "ht/jkm/photo/HEAD_ICON.jpg";
    private static final int REQUEST_CODE_TAKE_PHOTO = 1;
    private static final int REQUEST_CAMERA_CODE = 2;
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 0;
    private static final int MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD = 1;
    private String picturePath;

    private ArrayList<JsonNewBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private String[] industys = {"金融保险", "汽车交通", "房产服务", "医疗健康", "旅游", "游戏", "广告营销", "文化娱乐", "物流", "IT互联网"};
    private int[] industysId = {2, 3, 4, 5, 6, 7, 8, 9, 11, 12};
    private String[] hobbys = {"运动", "棋类", "旅游", "登山", "乐器", "音乐", "舞蹈", "饮茶", "影视", "阅读", "赋诗", "书法", "写作", "社交", "健身"};
    private DiaogPopup diaogPopup;
    private String user_id;
    private String userName;
    private String passWord;
    private String url;
    private String birthpalceId;
    private String corpAddressId;
    private String corpAddressName;
    private int Industry;
    private DiaogPopup.Builder builder;


    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {
        mTitleBarView.setTitleText("会员注册（2/2）");
    }

    @Override
    protected int initContentView() {
        UtilsStyle.setStatusBarMode(this, true);
        RxBarTool.FlymeSetStatusBarLightMode(getWindow(), true);
        RxBarTool.MIUISetStatusBarLightMode(getWindow(), true);
        return R.layout.activity_register_next;
    }

    @Override
    protected void initIntentData(Intent callIntent) {
        user_id = callIntent.getStringExtra("user_id");
        userName = callIntent.getStringExtra("userName");
        passWord = callIntent.getStringExtra("passWord");
    }

    @Override
    protected void initChildView() {
        mIvActivityRegisterHeadIcon = findViewById(R.id.iv_activity_register_head_icon);
        mIvActivityRegisterHeadIcon.setCircle(false);
        mEtActivityRegisterRealName = (EditText) findViewById(R.id.et_activity_register_real_name);
        mEtActivityRegisterQqInfo = (EditText) findViewById(R.id.et_activity_register_qq_info);
        mEtActivityRegisterWeixinInfo = (EditText) findViewById(R.id.et_activity_register_weixin_info);
        mBtmActivityRegisterPersonInfo = (ButtonItem) findViewById(R.id.btm_activity_register_person_info);
        mBtmActivityRegisterIndustry = (ButtonItem) findViewById(R.id.btm_activity_register_industry);
        mEtActivityRegisterCompany = (EditText) findViewById(R.id.et_activity_register_company);
        mBtmActivityRegisterCompanyAddress = (ButtonItem) findViewById(R.id.btm_activity_register_company_address);
        mEtActivityRegisterWant = (EditText) findViewById(R.id.et_activity_register_want);
        mBtnActivityRegisterNext = (TextView) findViewById(R.id.btn_activity_register_next);
    }

    @Override
    protected void initChildData() {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }

    @Override
    protected void setChildViewListener() {
        mIvActivityRegisterHeadIcon.setOnClickListener(this);
        mEtActivityRegisterRealName.setOnClickListener(this);
        mEtActivityRegisterQqInfo.setOnClickListener(this);
        mEtActivityRegisterWeixinInfo.setOnClickListener(this);
        mBtmActivityRegisterPersonInfo.setOnClickListener(this);
        mBtmActivityRegisterIndustry.setOnClickListener(this);
        mEtActivityRegisterCompany.setOnClickListener(this);
        mBtmActivityRegisterCompanyAddress.setOnClickListener(this);
        mEtActivityRegisterWant.setOnClickListener(this);
        mBtnActivityRegisterNext.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        String name = mEtActivityRegisterRealName.getText().toString().trim();
        switch (v.getId()) {
            case R.id.iv_activity_register_head_icon:
                try {
                    InputMethodManager im = (InputMethodManager) RegisterNextActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(RegisterNextActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture();
                    } else {
                        ActivityCompat.requestPermissions(RegisterNextActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(RegisterNextActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }
                break;
            case R.id.btm_activity_register_person_info:
                mBtmActivityRegisterPersonInfo.tv_des.setText("");
                mBtmActivityRegisterPersonInfo.iv_des.setVisibility(View.VISIBLE);
                ShowPickerView(mBtmActivityRegisterPersonInfo);
                break;
            case R.id.btm_activity_register_industry:
                builder = new DiaogPopup.Builder(this);
                int count = 0;
                for (String industy : industys) {
                    builder.addItem(count++, industy);
                }
                diaogPopup = builder.build();
                diaogPopup.setOnListPopupItemClickListener(new DiaogPopup.OnListPopupItemClickListener() {
                    @Override
                    public void onItemClick(int what) {
                        Industry = industysId[what];
                        mBtmActivityRegisterIndustry.tv_des.setText(industys[what]);
                        if (diaogPopup != null) {
                            diaogPopup.dismiss();
                        }
                    }
                });
                diaogPopup.showPopupWindow(mEtActivityRegisterRealName);//popuwindow特效
                break;
            case R.id.btm_activity_register_company_address:
                mBtmActivityRegisterCompanyAddress.tv_des.setText("");
                mBtmActivityRegisterCompanyAddress.iv_des.setVisibility(View.VISIBLE);
                ShowFullPickerView(mBtmActivityRegisterCompanyAddress);
                break;
            case R.id.btn_activity_register_next:
                if (TextUtils.isEmpty(name)) {
                    UIUtils.showToast("真实姓名不能为空");
                    return;
                }
                RegisterInfoBean registerInfoBean = new RegisterInfoBean();
//                registerInfoBean.mobile = user_id;
                registerInfoBean.name = name;//真实姓名
                registerInfoBean.avatar = url;//头像
                registerInfoBean.qq = mEtActivityRegisterQqInfo.getText().toString().trim();
                registerInfoBean.wechatId = mEtActivityRegisterWeixinInfo.getText().toString().trim();
                if (!TextUtils.isEmpty(birthpalceId)) {
                    registerInfoBean.birthpalceId = birthpalceId;//籍贯
                }
                if (Industry != 0) {
                    // TODO: 17/10/27 后台确认
                    registerInfoBean.corpIndustryId = Industry + "";//行业类型id
                }
                registerInfoBean.corpName = mEtActivityRegisterCompany.getText().toString().trim();//所在行业
                registerInfoBean.corpAddressId = corpAddressId;//单位所在地id
                registerInfoBean.corpAddressName = corpAddressName;//单位所在地名称
                registerInfoBean.lookForwardToMeet = corpAddressName;//期待结识
                showLoadingDialog();
                ApiManager.getApi().registerUpdateInfo(user_id, registerInfoBean).enqueue(new NetCallBack<RegisterInfoBean>() {
                    @Override
                    protected void onSuccess(Call<RegisterInfoBean> call, Response<RegisterInfoBean> response) {
                        RegisterInfoBean registerInfoBean1 = response.body();
                        UIUtils.showToast("注册成功");
                        Bundle bundle = new Bundle();
                        bundle.putString("userName", userName);
                        bundle.putString("passWord", passWord);
                        ActivityUtils.startActivityAndFinish(RegisterNextActivity.this, LoginActivity.class);
                    }

                    @Override
                    protected void hiddenProgress() {
                        hideLodingDialog();
                    }
                });
                break;
        }

    }


    private void takePicture() {
        DialogUtils.createPopwindow(this, "", "取消", new CustomPopwindow.OnBtnClickListener("拍照") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH);
                Uri data;
                // 判断版本大于等于7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
                    data = FileProvider.getUriForFile(RegisterNextActivity.this, "com.braveman.im.fileprovider", file);
                    // 给目标应用一个临时授权
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    data = Uri.fromFile(file);
                }
                intent.putExtra(MediaStore.EXTRA_OUTPUT, data);
                RegisterNextActivity.this.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);


            }
        }, new CustomPopwindow.OnBtnClickListener("从相册选择") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {

                Intent i = new Intent(
                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, REQUEST_CAMERA_CODE);
            }
        }).showAtLocation(mTitleBarView, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 130);
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        Toast.makeText(RegisterNextActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    Toast.makeText(RegisterNextActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(RegisterNextActivity.this, "Parse Failed", Toast.LENGTH_SHORT).show();
                    break;
                case 200: //图片
                    int type = (int) msg.obj;
                    String path = "";
                    switch (type) {
                        case 0:
                            path = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                            Glide.with(RegisterNextActivity.this)//
                                    .load(path)
                                    .into(mIvActivityRegisterHeadIcon);
                            toUpdata(path);
                            break;
                        case 1:
                            path = picturePath;
                            Glide.with(RegisterNextActivity.this)//
                                    .load(path)
                                    .into(mIvActivityRegisterHeadIcon);
                            toUpdata(path);
                            break;

                    }
            }
        }
    };

    private void toUpdata(String path) {
        File file = new File(path);
        final RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        showLoadingDialog();
        ApiManager.getApi().uploadPic("image", filePart).enqueue(new NetCallBack<List<PicUpdateBean>>() {


            @Override
            protected void onSuccess(Call<List<PicUpdateBean>> call, Response<List<PicUpdateBean>> response) {
                UIUtils.showToast("图片上传成功");
                if (response != null) {
                    if (response.body().size() != 0) {
                        PicUpdateBean picUpdateBean = response.body().get(0);
                        url = picUpdateBean.url;

                    }

                }
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture();
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takePicture();
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case REQUEST_CODE_TAKE_PHOTO:
                    String filePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                    new CompressPhotoThread(mHandler, filePath, 0).start();
                    break;
                //                 选择照片
                case REQUEST_CAMERA_CODE:
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    new CompressPhotoThread(mHandler, picturePath, 1).start();
                    break;

            }
        }

    }


    private void ShowPickerView(final ButtonItem buttonItem) {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(RegisterNextActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options2Items.get(options1).get(options2).name;
//                        +
//                        options3Items.get(options1).get(options2).get(options3);
                buttonItem.tv_des.setText(tx);
                buttonItem.iv_des.setVisibility(View.GONE);
                birthpalceId = options2Items.get(options1).get(options2).id;
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

//        /*pvOptions.setPicker(options1Items);//一级选择器

        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
//        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    // TODO: 2017/11/7 所在单位弹出选择器
    private void ShowFullPickerView(final ButtonItem buttonItem) {   // 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(RegisterNextActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options3Items.get(options1).get(options2).get(options3).name;
                buttonItem.tv_des.setText(tx);
                buttonItem.iv_des.setVisibility(View.GONE);
                corpAddressId = options3Items.get(options1).get(options2).get(options3).id;
                corpAddressName = options3Items.get(options1).get(options2).get(options3).name;
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

//        /*pvOptions.setPicker(options1Items);//一级选择器

//        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {   //解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(RegisterNextActivity.this, "province_new.json");//获取assets目录下的json文件数据

        ArrayList<JsonNewBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<JsonNewBean.ChildBeanX.ChildBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).child.size(); c++) {//遍历该省份的所有城市
                JsonNewBean.ChildBeanX.ChildBean childBean = new JsonNewBean.ChildBeanX.ChildBean();
                childBean.name = jsonBean.get(i).child.get(c).name;
                childBean.id = jsonBean.get(i).child.get(c).id;
                CityList.add(childBean);//添加城市

                ArrayList<JsonNewBean.ChildBeanX.ChildBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).child.get(c).name == null
                        || jsonBean.get(i).child.get(c).child.size() == 0) {
                    City_AreaList.add(new JsonNewBean.ChildBeanX.ChildBean());
                } else {

                    for (int d = 0; d < jsonBean.get(i).child.get(c).child.size(); d++) {//该城市对应地区所有数据
                        JsonNewBean.ChildBeanX.ChildBean childBean1 = new JsonNewBean.ChildBeanX.ChildBean();
                        childBean1.name = jsonBean.get(i).child.get(c).child.get(d).name;
                        childBean1.id = jsonBean.get(i).child.get(c).child.get(d).id;
                        City_AreaList.add(childBean1);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonNewBean> parseData(String result) {  //Gson 解析
        ArrayList<JsonNewBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonNewBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonNewBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
}